package com.shangyueshang.thread;

import java.util.concurrent.ThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/10/9 12:58
 * @version: v1.0.0
 */
@Slf4j
@EnableAsync
@Configuration
public class ThreadExecutorConfig {

    /**
     * 定义一个默认线程池, 用来异步执行流程
     *
     * @return
     */
    @Primary
    @Bean(ExecutorType.defaultExecutor)
    public ThreadPoolTaskExecutor defaultExecutor() {
        ThreadPoolTaskExecutor executor = new MyThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setTaskDecorator(new MDCTaskDecorator());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix(ExecutorType.defaultExecutor + "-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 定义一个线程池, 用来执行定时任务
     *
     * @return
     */
    @Bean(ExecutorType.scheduleExecutor)
    public ThreadPoolTaskExecutor scheduleExecutor() {
        ThreadPoolTaskExecutor executor = new MyThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(6);
        executor.setQueueCapacity(60);
        executor.setTaskDecorator(new MDCTaskDecorator());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix(ExecutorType.scheduleExecutor + "-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
